import { Button, Checkbox, Form, Input, Tabs, message as antdMessage } from "antd";
import React, { useEffect, useState } from "react";
import QRcode from "qrcode";
import axios from "axios";
import { useAppDispatch } from "../../app/hooks";
import { loginFail, loginSuccess } from "../../app/userInfo/userSlice";
import { useNavigate } from "react-router-dom";
const App = () => {
  const [url, setUrl] = useState("");
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const onFinish = async (values) => {
    console.log("Success:", values);
    
    const resp = await axios.post('/api/login', values)
    const { code, data, message } = resp.data;
    if(code === 200) {
      dispatch(loginSuccess(data))
      antdMessage.success(message)
      localStorage.setItem('token', data.token)
      navigate('/')
    } else {
      dispatch(loginFail())
      localStorage.removeItem('token')
      antdMessage.error(message)
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  useEffect(() => {
    QRcode.toDataURL("http://www.baidu.com").then((url) => {
      setUrl(url);
    });
  }, []);

  return (
    <div
      style={{
        width: 400,
        height: 400,
        position: "fixed",
        top: "40%",
        transform: "translateY(-50%)",
        right: 200,
      }}
    >
      <Tabs>
        <Tabs.TabPane tab="账户密码登录" key={1}>
          <Form
            name="basic"
            wrapperCol={{
              span: 16,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="Username"
              name="username"
              rules={[
                {
                  required: true,
                  message: "Please input your username!",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="Password"
              name="password"
              rules={[
                {
                  required: true,
                  message: "Please input your password!",
                },
              ]}
            >
              <Input.Password />
            </Form.Item>

     
            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Tabs.TabPane>
        <Tabs.TabPane tab="二维码登录" key={2}>
          <img src={ url } alt="" width="400"/>
        </Tabs.TabPane>
      </Tabs>
    </div>
  );
};

export default App;
